package com.richper.springcloudh2020.lb.impl;

import com.richper.springcloudh2020.lb.LoadBalance;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

@Component
public class MyRule implements LoadBalance {
    private AtomicInteger visit = new AtomicInteger(0);

    private int getVisit(){
        for (;;){
            int curr = visit.get();
            int next = curr >= Integer.MAX_VALUE ? 0 : curr+1;
            if (visit.compareAndSet(curr,next)) {
                return next;
            }
        }
    }

    @Override
    public ServiceInstance instance(List<ServiceInstance> instances) {
        return instances.get(getVisit() % instances.size());
    }
}
